package ${package}.service;

import ${package}.dao.AuthorityDao;
import ${package}.dao.UserDao;
import ${package}.exception.UserServiceException;
import ${package}.model.entity.Authority;
import ${package}.model.entity.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ${moduleName}Service implementation.
 */
@Service
public class ${moduleName}ServiceImpl implements ${moduleName}Service {
    /**
     * Service logger.
     */
    private Log logger = LogFactory.getLog(this.getClass());

    /**
     * Service info string.
     */
    public static final String SERVICE_INFO = ${moduleName}ServiceImpl.class.getName() + ", $Revision: $";


    @Override
    public String getServiceInfo() {
        logger.debug(${moduleName}ServiceImpl.class.getName() + " Info requested.");

        return SERVICE_INFO;
    }

    /**
     * Autowired UserDao instance.
     */
    @Autowired
    private UserDao userDao;

    /**
     * Autowired AuthorityDao instance.
     */
    @Autowired
    private AuthorityDao authorityDao;

    @Override
    public User saveUser(String username, String password, String authority) {
        Authority authorityByName = authorityDao.getByAuthority(authority);
        // check authority exists
        if (authorityByName == null) {
            authorityByName = new Authority(authority);
            authorityDao.save(authorityByName);
        }

        if (!isUsernameAvailable(username)) {
            throw new ${moduleName}ServiceException("Username is already taken: " + username);
        }

        User user = new User(username, password, true);
        user.getAuthorities().add(authorityByName);

        userDao.save(user);
        return user;
    }

    @Override
    public boolean isUsernameAvailable(String username) {
        return (userDao.getByUsername(username) == null);
    }
}
